const app = getApp();
const WxParse = require('../wxParse/wxParse')
import {
  getMenu,
  getStickyList,
  getTopicList,
  getCircleList,
  getDetail,
  getRelateForum,
  getTopicsTags,
  addForums,
  deletePost,
  deleteComment,
  getFollowForums,
  getUserForum,
  creatCircles,
  getAuditList,
  verifyAudits,
  getCircleByID,
  getVideoLists,
  getCircleByMines,
  joinCircles,
  quitCircles,
  getLocationPosts,
  getsignLists,
  getReview,
  reviewPost,
  reviewComment,
  auditCirclePost,
  getCommentsReview,
  getMemberlist,
  qrcodeLogin,
  creditSubscribe,
  getRandTopic
} from "../api/forum";

import {
  fav,
  like,
  updateFollow
} from "../api/common.js";




/**
 * 获取置顶文章
 */

const getStickyLists = function (args) {
  getStickyList(args).then(res => {
      let args = {}
      if (res.length == 0) {
        this.setData({
          stickyNodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          isStickeyLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isPull) {
        args.sticky =  this.data.sticky.concat(res)
        args.stickypage = this.data.stickypage + 1
      } else if (this.data.isBottom) {
        args.sticky =  this.data.sticky.concat(res)
        args.stickypage = this.data.stickypage + 1
      } else {
        args.sticky = res
        args.stickypage = this.data.stickypage + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      args.topicload=false;
      args.loading = true;
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
    })
}


/**
 * 获取最新帖子
 */

const getTopicLists = function (args) {
  getTopicList(args).then(res => {
      let args = {}
      if (res.length == 0) {
        this.setData({
          topicNodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isPull) {
        args.posts = this.data.posts.concat(res)
        args.page = this.data.page + 1
      } else if (this.data.isBottom) {
        args.posts = this.data.posts.concat(res)
        args.page = this.data.page + 1
      } else {
        args.posts = res
        args.page = this.data.page + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      args.searchViewVisible=false;
      args.topicload = false;
      args.isPull = false;
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}



/**
 * 获取菜单栏目
 * @param {*} e 
 */

const getMenus = function () {
  let that = this;
  getMenu().then(res => {
    let args = {};
    if (res.status == 200) {
      args.menu = res.data
      that.setData(args)
    }
  })
}

/**
 * 预览图片
 */

const previewImgFunc = function (e) {
  var imageslist = e.currentTarget.dataset.list;
  var src = e.currentTarget.dataset.src;

  wx.previewImage({
    current: src,
    urls: imageslist,
  })
}





const getRandTopicList = function () {
  getRandTopic().then(res => {
      let args = {}
      console.log(res);
      if (this.data.isPull) {
        args.posts = this.data.posts.concat(res)
      } else {
        args.nowNote = res[1]
        args.posts = res
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      if (args.posts != []) {
        args.isList = true
      }
      args.loading = true;
      args.showLoading = false;
      args.topicload = false;
      args.isPull = false;
      args.searchViewVisible = false;
      this.setData(args)
    })
    .catch(err => {})
}



const getReviewLists = function (args) {
  getReview(args).then(res => {
      let args = {}
      if (res.length == 0) {
        this.setData({
          nodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isPull) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.nowNote = res[1]
        args.posts = res
        args.page = this.data.page + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      if (args.posts != []) {
        args.isList = true
      }
      args.loading = true;
      args.showLoading = false;
      args.topicload = false;
      args.isPull = false;
      args.searchViewVisible = false;
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}



/**
 * 列表点赞
 */
const taplikes = function (e) {
  let args = {}
  let that = this;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return;
  }
  args.id = e.currentTarget.id;
  let index = e.currentTarget.dataset.index
  like(args).then(res => {
    if (res.status === 200) {
      this.data.posts[index].islike = true;
      this.data.posts[index].likes = this.data.posts[index].likes + 1;
      that.setData({
        posts: this.data.posts,
      })
    } else if (res.status == 202) {
      this.data.posts[index].islike = false;
      this.data.posts[index].likes = this.data.posts[index].likes - 1;
      that.setData({
        posts: this.data.posts,
      })

    }
  }).catch(err => {
    console.log(err)
    if (err.message = "授权信息有误") {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })
}

/**
 * 列表收藏
 */
const tapfavs = function (e) {
  let args = {}
  let that = this;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return;
  }
  args.id = e.currentTarget.id;
  let index = e.currentTarget.dataset.index
  fav(args).then(res => {
    if (res.status === 200) {
      this.data.posts[index].isfav = true;
      this.data.posts[index].favs = this.data.posts[index].favs + 1;
      that.setData({
        posts: this.data.posts,
      })
    } else if (res.status == 202) {
      this.data.posts[index].isfav = false;
      this.data.posts[index].favs = this.data.posts[index].favs - 1;
      that.setData({
        posts: this.data.posts,
      })

    }
  }).catch(err => {
    console.log(err)
    if (err.message = "授权信息有误") {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })
}




/** 解析视频 */
const getVideoUrl = function (e) {

  var t = e.currentTarget.dataset.id;
  var url = e.currentTarget.dataset.video;
  var index = e.currentTarget.dataset.index;
  let that = this;
  that.setData({
    video: '',
  })
  wx.request({
    url: 'https://mall.guqule.com/mp/video.php',
    data: {
      url: url,
    },
    method: 'get',
    success: function (res) {
      if (res.data.status == 200) {
        that.data.posts[index].media.videourl = res.data.url;
        that.data.posts[index].isplay = true;
        that.setData({
          posts: that.data.posts,
        })
        if (that.data.videoId) {
          wx.createVideoContext(that.data.videoId).stop(), t == that.data.videoId;
          that.setData({
            videoId: t
          }), wx.createVideoContext(t).play();
        } else that.setData({
          videoId: t
        }), wx.createVideoContext(t).play();
      }
    }
  })

}

const VideoPlay = function (e) {
  var t = e.currentTarget.dataset.id;
  if (this.data.videoId) {
    if (wx.createVideoContext(this.data.videoId).stop(), t == this.data.videoId) return void this.setData({
      videoId: null
    });
    this.setData({
      videoId: t
    }), wx.createVideoContext(t).play();
  } else this.setData({
    videoId: t
  }), wx.createVideoContext(t).play();
}



/**
 * 
 * 获取圈子列表
 */
const getCircleLists = function (args) {
  var that = this;
  getCircleList(args).then(res => {
      let args = {}
      args.showloading = false;
      args.parent = res[0].id;
      args.cats = [].concat(this.data.cats, res)
      if (res[0].subterms.length > 0) {
        args.id = res[0].id;
        this.getSubCieclelist({
          parent: res[0].id
        })
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      //this.setData({isMessage:true})
    })
}

/**
 * 获取子列表
 * @param {*} obj 
 */
const getSubCieclelist = function (args) {
  getCircleList(args).then(res => {
      let args = {}
      args.showloading = false;
      if (res.length == 0) {
        this.setData({
          nodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isBottom) {
        args.subcats = [].concat(this.data.subcats, res)
        args.page = this.data.page + 1
      } else {
        args.subcats = res
        args.page = this.data.page + 1
      }
      args.loading = true;
      args.subcatsloading = false;
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      this.setData({
        isMessage: true
      })
    })
}


/**
 * 
 * 获取文章详情
 */

const getForumDetails = function () {
  let id = this.data.id;
  let type = this.data.type;
  let that = this;
  getDetail(id, type).then(res => {
      let args = {}
      let current = getCurrentPages()
      if (current.length === 1) {
        args.isShare = true
      }
      args.showloading = false
      if (type == 'forums' && res.format != 'quote') {
        WxParse.wxParse('article', 'html', res.content.rendered.replace(/<img.*\/>/ig, ""), this, 5)
      } else {
        WxParse.wxParse('article', 'html', res.content.rendered, this, 5)
      }
      args.isPull = false
      //args.isShow = true
      args.detail = res
      args.isLike = res.islike;
      args.isFav = res.isfav;
      args.isFollow = res.author.status == 'disfollow';
      if (res.isvote) {
        let count = 0
        for (let i = 0; i < res.vote.options.length; i++) {
          count += res.vote.options[i].count;
        }
        args.count = count
      }
      args.showSkeleton = false
      if (res.format == 'video' && res.media.video) {
        that.videoplay(res.media.video);
        this.videoContext = wx.createVideoContext('videoid');
      }
      let videoAdLogs = wx.getStorageSync('videoAdLogs') || [];
      if (videoAdLogs.indexOf(this.data.id) > -1) {
        args.we_video_ad = false
      } else {
        args.we_video_ad = res.we_video_ad
      }
      this.getRelateForums(id, type)
      // this.getDetailAds()
      this.setData(args)
      // 阅读记录缓存数据
      let record = {}
      let title = {}
      let excerpt = {}
      let categories = []
      let cate = {}
      let meta = {}
      record.id = res.id
      record.type = res.type
      record.date = res.date
      title.rendered = res.title.rendered
      excerpt.rendered = res.excerpt.rendered
      meta = res.meta
      record.meta = meta
      record.comments = res.comments
      record.favs = res.favs
      record.likes = res.likes
      record.title = title
      record.excerpt = excerpt
      record.categories = categories
      // 调用 API 从本地缓存中获取阅读记录并记录
      let logs = wx.getStorageSync('readLogs') || []
      let readsave = true
      // 过滤重复值
      if (logs.length > 0) {
        for (let i = 0; i < logs.length; i++) {
          if (logs[i].id == res.id) {
            readsave = false
            break;
          }
        }
      }
      if (readsave) {
        logs.unshift(record)
      }
      // 如果超过指定数量
      if (logs.length > 9) {
        logs.pop(); // 去除最后一个
      }
      wx.setStorageSync('readLogs', logs)
      //阅读记录缓存结束
      wx.stopPullDownRefresh()
    })
    .catch(err => {
      if (this.data.isPull) {
        this.setData({
          isPull: false
        })
        wx.stopPullDownRefresh()
      }
      console.log(err)
    })
}

const getRelateForums = function (id, type) {
  getRelateForum(id, type).then(res => {
    let args = [];
    args.relatePost = res;
    this.setData(args)
  })

}


/**
 * 扫码登陆
 */
const scanQrcode = function () {
  let user = app.globalData.user
  if (user) {
    wx.scanCode({
      scanType: ['qrCode'],
      success: res => {
        //console.log(res)
        let qrcode = res.result;
        if (qrcode.length != 16) {
          wx.showToast({
            icon: 'none',
            title: '无效的二维码'
          })
          return;
        }
        let args = {}
        args.session = qrcode
        args.action = 'scan'
        qrcodeLogin(args).then(data => {
            //console.log(data)
            if (data.success == true) {
              wx.showModal({
                title: '请确认',
                content: '确认使用' + user.nickName + '的账号登录网站？',
                cancelColor: '#D0104C',
                confirmColor: '#D0104C',
                confirmText: '确认登录',
                success: response => {
                  if (response.confirm) {
                    args.action = 'confirm'
                    qrcodeLogin(args).then(result => {
                      if (result.status == 200) {
                        wx.showToast({
                          title: '已经登录',
                          icon: 'success',
                          duration: 1000
                        })
                        app.globalData.user = res.user;
                        wx.setStorageSync('user', res.user);
                        if (res.access_token) {
                          wx.setStorageSync('token', res.access_token);
                          wx.setStorageSync('expired_in', Date.now() + parseInt(res.expired_in, 10) * 100000 - 60000);
                        }
                      } else {
                        wx.showToast({
                          title: '登录失败',
                          icon: 'success',
                          duration: 1000
                        })
                      }
                    })
                  }
                }
              })
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    })
  }
}



/**
 * 积分阅读
 */

const creditRead = function (e) {
  let args = {}
  let that = this
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return
  }
  args.id = this.data.detail.id
  args.payment = 'credit'
  args.expenses = e.currentTarget.dataset.credit
  wx.showModal({
    title: '温馨提示',
    content: '确认使用 ' + e.currentTarget.dataset.credit + ' 积分阅读本篇文章?',
    cancelColor: '#D0104C',
    confirmColor: '#D0104C',
    confirmText: '确认',
    success: response => {
      if (response.confirm) {
        creditSubscribe(args).then(res => {
            wx.showToast({
              title: res.message,
              icon: 'success',
              duration: 1000
            })
            if (res.status == 200) {
              that.getForumDetails()
            }
          })
          .catch(err => {
            if (err.data.status = 403) {
              wx.showModal({
                title: '温馨提示',
                showCancel: false,
                content: err.message + ', 确定刷新页面？',
                success: response => {
                  that.getForumDetails()
                }
              })
            } else {
              wx.showModal({
                title: '温馨提示',
                showCancel: false,
                content: err.message
              })
            }
          })
      } else {
        wx.showToast({
          title: '取消完成',
          icon: 'success',
          duration: 1000
        })
      }
    }
  })
}



const gotoPddDetail = function (e) {
  let id = e.currentTarget.dataset.pdd;
  wx.navigateTo({
    url: '/pages/shop/pddetail?share=true&id=' + id,
  })
}

const getTagList = function (args) {
  getTopicsTags(args).then(res => {
    let args = {}
    if (res.length < 10) {
      args.isTagLastPage = true
    }
    if (this.data.isBottom) {
      args.isBottom = false
      args.tags = [].concat(this.data.tags, res)
      args.tagpage = this.data.tagpage + 1
    } else {
      args.tags = [].concat(this.data.tags, res)
      args.tagpage = this.data.tagpage + 1
    }
    this.setData(args)
  })
}


/**
 * 发布内容
 */

const creatForums = function () {
  let that = this;
  let content = this.data.textinput
  let images = this.data.imagesubject
  let type = this.data.type;
  let topic = this.data.topic;
  let title = this.data.title;
  let tags = "";
  let args = {}

  if (this.data.tags.length > 1) {
    tags = this.data.tags.join(',');
  } else {
    tags = this.data.tags[0];
  }
  args.meta = {}
  args.meta.custom = this.data.custom
  if (this.data.isAddNetDisk) {
    if (this.data.NetDiskLink[0].link == "") {
      wx.showModal({
        title: '提示',
        content: '内容不能为空'
      })
      return
    } else {
      args.meta.NetDisk = this.data.NetDiskLink
    }
  }
  if (this.data.shop) {
    args.meta.shop = this.data.shop
  }

  if (!this.data.anonymity) {
    args.meta.anonymity = 1
  }

  if (content == '' || content == null) {
    wx.showModal({
      title: '提示',
      content: '内容不能为空'
    })
    return
  }
  if (title == '' || title == null) {
    title = content.slice(0, 20);
  }
  if (topic == '' || topic == null) {
    wx.showModal({
      title: '提示',
      content: '请选择分类'
    })
    return
  }
  if (this.data.attachmentInfo) {
    args.mtitle = this.data.attachmentInfo.name;
    args.document = this.data.attachmentInfo.path;
  }

  if (this.data.location) {
    args.longitude = this.data.location.longitude;
    args.latitude = this.data.location.latitude;
    args.location = this.data.location.address
  }
  if (this.data.audioInfo) {
    args.duration = this.data.audioInfo.duration
    args.displayDuration = this.data.audioInfo.second
    args.audio = this.data.audioInfo.tempFilePath
  }
  if (this.data.video) {
    args.video = this.data.video
  }
  if (this.data.goods_id) {
    args.goods_id = this.data.goods_id
  }
  args.title = title
  args.circle = topic
  args.category = topic
  args.type = type
  args.format = this.data.format
  args.content = content
  args.images = images
  args.topic = tags

  if (!this.data.user) {
    that.data.currentConfig.show = true;
    that.setData({
      bounced: false,
      currentConfig: that.data.currentConfig,
    })
  } else {
    wx.showLoading({
      title: "正在发布",
      mask: true,
    })
    addForums(type, args).then(res => {
        if (res.status === 200) {
          let templates = app.globalData.templates.posts;
          wx.requestSubscribeMessage({
            tmplIds: templates,
            success(res) {
              let template_id = JSON.stringify(res)
              for (let i = 0; i < templates.length; i++) {
                let template = templates[i]
                let response = template_id.replace(template, "status")
                let subscribe = JSON.parse(response)
                app.vPush.addFormId(template, subscribe.status)
              }
              if (res.errMsg == "requestSubscribeMessage:ok") {
                wx.showToast({
                  // title: '订阅消息完成',
                  icon: 'success',
                  duration: 1000
                })
              }
            },
            fail: function (res) {


            }
          })
          this.setData({
            content: "",
            topic: "",
            files: "",
            images: "",
          })
          wx.hideLoading();
          setTimeout(function () {
            wx.showToast({
              title: res.message,
              icon: 'success',
              duration: 900,
            })
          }, 900)
          wx.navigateBack({
            delta: 3
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '发布失败，请稍后重试'
          })
        }
      })
      .catch(err => {
        if (err.message == "未授权登录用户不能发布内容") {
          that.data.currentConfig.show = true;
          that.setData({
            bounced: false,
            currentConfig: that.data.currentConfig,
          })
        }
        wx.hideLoading();
      })
  }
}

/**
 * 删除已发布
 */

const bouncedDeleteTap = function (e) {
  let that = this;
  let type = e.currentTarget.dataset.type;
  deletePost(this.data.id, type).then(res => {
    if (res.status == 200) {
      that.setData({
        bounced: false,
      })
      that.data.posts.splice(that.data.delindex, 1);
      that.setData({
        posts: that.data.posts,
      })
      wx.showToast({
        title: '删除成功',
      })
    }
    if (res.status == 400) {
      that.setData({
        bounced: false,
      })
      wx.showToast({
        title: '删除失败',
      })
    }
  }).catch(err => {
    if (err.message == "未授权登录用户,不能删除文章") {
      that.data.currentConfig.show = true;
      that.setData({
        bounced: false,
        currentConfig: that.data.currentConfig,
      })
    }
  })
}


/**
 * 删除
 */

const bouncedCDeleteTap = function (e) {
  let that = this;
  deleteComment(this.data.id).then(res => {
    if (res.status == 200) {
      that.setData({
        bounced: false,
      })
      that.data.posts.splice(that.data.delindex, 1);
      that.setData({
        posts: that.data.posts,
      })
      wx.showToast({
        title: '删除成功',
      })
    }
    if (res.status == 400) {
      that.setData({
        bounced: false,
      })
      wx.showToast({
        title: '删除失败',
      })
    }
  }).catch(err => {
    if (err.message == "未授权登录用户,不能删除文章") {
      that.data.currentConfig.show = true;
      that.setData({
        bounced: false,
        currentConfig: that.data.currentConfig,
      })
    }
  })
}

const reviewPosts = function () {
  let that = this;
  let args = {
    post_id: this.data.id,
    post_status: 'publish',
    id:this.data.id,
    status:'publish'
  }
  let type=this.data.type;
  console.log(type);
  reviewPost(args, type).then(res => {
    if (res.status == 200) {
      that.setData({
        bounced: false,
        showDialog:false,
      })
      that.data.posts.splice(that.data.delindex, 1);
      that.setData({
        posts: that.data.posts,
      })
      wx.showToast({
        title: '审核通过',
      })
    }
    if (res.status == 400) {
      that.setData({
        bounced: false,
      })
      wx.showToast({
        title: '审核失败',
      })
    }
  }).catch(err => {
    if (err.message == "未授权登录用户,不能删除文章") {
      that.data.currentConfig.show = true;
      that.setData({
        bounced: false,
        currentConfig: that.data.currentConfig,
      })
    }
  })
}


const reviewComments = function () {
  let that = this;
  let args = {
    comment_id: this.data.id,
    approved: '1',
  }
  reviewComment(args).then(res => {
    if (res.status == 200) {
      that.setData({
        bounced: false,
      })
      that.data.posts.splice(that.data.delindex, 1);
      that.setData({
        posts: that.data.posts,
      })
      wx.showToast({
        title: '审核通过',
      })
    }
    if (res.status == 400) {
      that.setData({
        bounced: false,
      })
      wx.showToast({
        title: '审核失败',
      })
    }
  }).catch(err => {
    if (err.message == "未授权登录用户,不能删除文章") {
      that.data.currentConfig.show = true;
      that.setData({
        bounced: false,
        currentConfig: that.data.currentConfig,
      })
    }
  })
}


/**
 * 获取我的关注
 */

const getFollowForum = function (data) {
  let args = [],
    that = this;
  getFollowForums(data).then(res => {
      if (res.code == "error") {

      } else {
        if (res.length < 10) {
          this.setData({
            isLastPage: true,
            loadtext: '到底啦',
          })
        }
        if (this.data.isPull) {
          args.posts = this.data.posts.concat(res)
          args.page = this.data.page + 1
        } else if (this.data.isBottom) {
          args.posts = this.data.posts.concat(res)
          args.page = this.data.page + 1
        } else {
          args.posts = res
          args.page = this.data.page + 1
        }
        if (this.data.isPull) {
          wx.stopPullDownRefresh()
        }
        args.topicload = false;
        args.isPull = false;
        this.setData(args)
      }
    })
    .catch(err => {
      if (err.message == '未授权登录用户无法获取关注数据') {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
    })
}


/**
 * 获取发过的帖子
 */

const getUserArticle = function (data) {
  let args = {},
    that = this
  getUserForum(data).then(res => {
      if (res.status == 500) {
        this.setData({
          isLastPage: true,
          loadtext: '该用户暂时未发布任何内容',
        })

      } else {
        let args = {}
        args.showloading = false;
        if (res.length == 0) {
          this.setData({
            nodate: true
          })
        }
        if (res.length < 10) {
          this.setData({
            nodata: true,
            showloadmore: false,
            isLastPage: true,
            loadtext: '到底啦'
          })
        }
        if (this.data.isPull) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
        } else if (this.data.isBottom) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
        } else {
          args.nowNote = res[1]
          args.posts = res
          args.page = this.data.page + 1
        }
        if (this.data.isPull) {
          wx.stopPullDownRefresh()
        }
        if (args.posts != []) {
          args.isList = true
        }
        args.loading = true;
        args.showLoading = false;
        args.topicload = false;
        args.isPull = false
        this.setData(args)
      }
    })
    .catch(err => {
      console.log(err)
    })
}

const creatCircle = function (data) {
  if (!this.data.protocolChecked) {
    wx.showToast({
      title: '请阅读并确定圈主协议',
    })
    return
  }
  if (this.data.imagesubject == null) {
    wx.showToast({
      title: '请上传封面',
    })
    return
  }
  if (this.data.circleName == "") {
    wx.showToast({
      title: '请输入圈子名称',
    })
    return
  }
  if (this.data.circleDesc == "") {
    wx.showToast({
      title: '请输入圈子描述',
    })
    return
  }
  wx.showLoading({
    title: '创建圈子中'
  });
  let datas = {
    name: this.data.circleName,
    parent: this.data.parent,
    cover: this.data.imagesubject,
    description: this.data.circleDesc,
  }
  creatCircles(datas).then(res => {
    wx.hideLoading({
      success: (res) => {
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 900,
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 3
          })
        }, 3000)
      },
    })


  }).catch(err => {
    wx.hideLoading();
    wx.showToast({
      title: '您已创建过圈子了',
    })
  })


}

const getCircleAuditList = function (args) {
  getAuditList(args).then(res => {
    let args = {}
    if (res.length < 10) {
      args.isLastPage = true
    }
    if (this.data.isBottom) {
      args.isBottom = false
      args.auditList = [].concat(this.data.auditList, res)
      args.page = this.data.page + 1
    } else {
      args.auditList = [].concat(this.data.auditList, res)
      args.page = this.data.page + 1
    }
    this.setData(args)
  })
}


const verifyAudit = function (args) {
  verifyAudits(args).then(res => {
    wx.showToast({
      title: res.message,
    })
    this.setData({
      showDialog: false,
      auditList: [],
      page: 1,
    })
    this.getCircleAuditList();

  })
}


const getCircleByIDs = function (id) {
  getCircleByID(id).then(res => {
      let args = {}
      args.count = res.count
      args.category = res.name
      if (res.color) {
        args.color = res.color
      }
      args.isCircle = res.isCircle
      //  args.subcates = res.subcate
      args.description = res.description
      args.followers = res.followers
      args.cover = res.cover
      args.boardmaster = res.boardmaster
      args.circleloading = false
      this.setData(args)
      wx.setNavigationBarTitle({
        title: res.name
      })
      let circlehistory = {}
      circlehistory.name = res.name
      circlehistory.id = res.id
      circlehistory.cover = res.cover
      // 调用 API 从本地缓存中获取阅读记录并记录
      let logs = wx.getStorageSync('circlehistory') || []
      let readsave = true
      // 过滤重复值
      if (logs.length > 0) {
        for (let i = 0; i < logs.length; i++) {
          if (logs[i].id == res.id) {
            logs.splice(i, 1);
          }
        }
      }
      if (readsave) {
        logs.unshift(circlehistory)
      }
      // 如果超过指定数量
      if (logs.length > 9) {
        logs.pop(); // 去除最后一个
      }
      wx.setStorageSync('circlehistory', logs)
    })
    .catch(err => {
      console.log(err)
    })
}

const getVideoList = function (data) {
  let args = {},
    that = this;
  getVideoLists(data).then(res => {
      if (res.status == 500) {
        this.setData({
          isLastPage: true,
          loadtext: '该用户暂时未发布任何内容',
        })

      } else {
        if (res.length < 10) {
          this.setData({
            isLastPage: true,
            loadtext: '到底啦',
          })
        }
        if (this.data.isPull) {
          args.posts = this.data.posts.concat(res)
          args.page = this.data.page + 1
        } else if (this.data.isBottom) {
          args.posts = this.data.posts.concat(res)
          args.page = this.data.page + 1
        } else {
          args.posts = res
          args.page = this.data.page + 1
        }
        that.setData(args);
      }
    })
    .catch(err => {
      console.log(err)
    })
}

/**
 * 我关注的圈子 
 * */
const getCircleByMine = function (data) {
  let that = this;
  let args = []
  getCircleByMines(data).then(res => {
    if (res.length < 10) {
      this.setData({
        isLastmyPage: true,
        loadtext: '到底啦',
      })
    }
    if (this.data.isBottoms) {
      args.join = that.data.join.concat(res);
      args.mypages = this.data.mypages + 1;
    } else {
      args.join = res;
      args.mypages = this.data.mypages + 1;
    }
    that.setData(args);
  }).catch(err => {
    if (err.message == '授权信息有误') {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })

}


/**
 * 关注圈子
 */

const joinCircle = function (e) {
  var that = this;
  let args = [];
  var id = e.currentTarget.id;
  let type = e.currentTarget.dataset.type;
  let index = e.currentTarget.dataset.index;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return;
  }
  joinCircles(id).then(res => {
    if (res.status == 200) {
      if (type == 'list') {
        that.data.subcats[index].isCircle = true;
        args.subcats = that.data.subcats;
      }
      args.isCircle = true;
      wx.showToast({
        title: res.message,
      })
      that.setData(args);
    } else {
      wx.showToast({
        title: res.message,
      })
    }
  }).catch(err => {
    if (err.message = "授权信息有误") {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })
}

/**
 * 关注圈子
 */

const quitCircle = function (e) {
  var that = this;
  let args = [];
  var id = e.currentTarget.id;
  let type = e.currentTarget.dataset.type;
  let index = e.currentTarget.dataset.index;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return;
  }
  quitCircles(id).then(res => {
    if (res.status == 200) {
      if (type == 'list') {
        that.data.subcats[index].isCircle = false;
        args.subcats = that.data.subcats;
      }
      args.isCircle = false;
      wx.showToast({
        title: res.message,
      })
      that.setData(args);
    } else {
      wx.showToast({
        title: res.message,
      })
    }
  }).catch(err => {
    if (err.message = "授权信息有误") {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })
}

/**
 * 获取附近的文章
 */

const getLocationPost = function (t, a) {
  var i = this,
    n = i.data.screenRatio;
  getLocationPosts(t, a).then(function (t) {
    i.setData({
      posts: t,
    })
    if (t && t.length > 0) {
      for (var e = t, a = [], r = [], s = [], o = 0, c = 10, u = i.data.curCenter, l = 0; l < e.length; l++) {
        var d = parseFloat(e[l].meta.latitude),
          h = parseFloat(e[l].meta.longitude);
        if (u.length > 0 && (0 != Math.round(u[1]) || 0 != Math.round(u[0]))) {
          var g = i.getDistance(u[1], u[0], d, h);
          g < c && (o = l, c = g), e[l].distance = g > 0 ? g.toFixed(1) : 0;
        }
        e[l].isAttend = 0;
        var f = {
          id: e[l].id,
          iconPath: i.getUserAvatarBg(e[l].author.gender),
          latitude: d,
          longitude: h,
          width: Math.floor(45 / n),
          height: Math.floor(60 / n),
          alpha: 1,
          calloutCopy: i.getMarkerTip()
        };
        a.push(f);
        var v = {
          latitude: e[l].meta.latitude,
          longitude: e[l].meta.longitude
        };
        r.push(v), s.push(e[l].userid);
      }
      i.setData({
        markers: a,
        includePoints: r,
        curDiscovery: 0,
        discoveryTotal: e.length,
        userList: e
      }), i.getUserAvatar(e);
    } else i.resetDiscoveryData();
  });
}

const getsignList = function (arg) {
  let args = {},
    that = this;
  getsignLists(arg).then(res => {
      if (res.status == 500) {
        this.setData({
          isLastPage: true,
          loadtext: '该用户暂时未发布任何内容',
        })

      } else {
        if (res.length < 10) {
          this.setData({
            isLastPage: true,
            loadtext: '到底啦',
          })
        }
        if (this.data.isPull) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
        } else if (this.data.isBottom) {
          args.posts = [].concat(this.data.posts, res)
          args.page = this.data.page + 1
        } else {
          args.posts = res
          args.page = this.data.page + 1
        }
        if (this.data.isPull) {
          wx.stopPullDownRefresh()
        }
        if (args.posts != []) {
          args.isList = true
        }
        args.showSkeleton = false;
        args.isPull = false
        this.setData(args)
      }
    })
    .catch(err => {
      if (err.message = "没有授权登录无法查看") {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
    })
}


const getCircleAudit = function (args) {
  let that=this;
  auditCirclePost(args).then(res => {
      let args = {}
      if (res.length == 0) {
        this.setData({
          topicNodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isPull) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.posts = res
        args.page = this.data.page + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      if (args.posts != []) {
        args.isList = true
      }
      args.loading = true;
      args.showLoading = false;
      args.topicload = false;
      args.isPull = false;
      args.searchViewVisible = false;
      this.setData(args)
    })
    .catch(err => {
      this.setData({
        isMessage: true
      })
      if (err.message = "授权信息错误, 无法查看话题") {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
      wx.stopPullDownRefresh()
    })
}



const getCommentList = function (args) {
  getCommentsReview(args).then(res => {
      let args = {}
      args.showloading = false;
      if (res.length == 0) {
        this.setData({
          nodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isPull) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.posts = res
        args.page = this.data.page + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      if (args.posts != []) {
        args.isList = true
      }
      args.showSkeleton = false;
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })
}

const openmap = function (e) {
  var lng = parseFloat(e.currentTarget.dataset.lng);
  var lat = parseFloat(e.currentTarget.dataset.lat);
  var location = e.currentTarget.dataset.location;
  wx.openLocation({
    latitude: lat,
    longitude: lng,
    location: location
  })
}


const getMenmberList = function (id, data) {
  let that = this;
  let args = {};
  getMemberlist(id, data).then(res => {
      if (res.length < 10) {
        this.setData({
          isMenmberLastPage: true,
          loadtext: '到底啦',
        })
      }
      if (this.data.bottom) {
        args.mempage = this.data.mempage + 1
        args.memberList = [].concat(this.data.memberList, res)
      } else {
        args.mempage = this.data.mempage + 1;
        args.memberList = res;
      }
      that.setData(args);
    })
    .catch(err => {
      console.log(err)
    })
}

/***
 * 跳转用户信息
 */

 const userTap=function(e){
  var id=e.currentTarget.id;
  wx.navigateTo({
    url: '/pages/user/user?id='+id,
  })

 }

/**
 * 
 * 获取圈子列表
 */
const getCircleListss = function (args) {
  var that = this;
  getCircleList(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isBottom) {
        args.catsList = [].concat(this.data.catsList, res)
        args.page = this.data.page + 1
      } else {
        args.catsList = res
        args.page = this.data.page + 1
      }
      args.loading = true;
      args.subcatsloading = false;
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
    })
}

module.exports = function (obj) {
  obj.getTopicLists = getTopicLists;
  obj.getStickyLists = getStickyLists;
  obj.getMenus = getMenus;
  obj.previewImgFunc = previewImgFunc;
  obj.getVideoUrl = getVideoUrl;
  obj.tapfavs = tapfavs;
  obj.taplikes = taplikes;
  obj.getCircleLists = getCircleLists;
  obj.getSubCieclelist = getSubCieclelist;
  obj.getForumDetails = getForumDetails;
  obj.getRelateForums = getRelateForums;
  obj.gotoPddDetail = gotoPddDetail;
  obj.getTagList = getTagList;
  obj.creatForums = creatForums;
  obj.bouncedDeleteTap = bouncedDeleteTap;
  obj.bouncedCDeleteTap = bouncedCDeleteTap
  obj.getFollowForum = getFollowForum;
  obj.getUserArticle = getUserArticle;
  obj.creatCircle = creatCircle;
  obj.getCircleAuditList = getCircleAuditList;
  obj.verifyAudit = verifyAudit;
  obj.getCircleByIDs = getCircleByIDs;
  obj.getVideoList = getVideoList;
  obj.getCircleByMine = getCircleByMine;
  obj.joinCircle = joinCircle;
  obj.quitCircle = quitCircle;
  obj.getLocationPost = getLocationPost;
  obj.getsignList = getsignList;
  obj.getReviewLists = getReviewLists;
  obj.reviewPosts = reviewPosts;
  obj.getCircleAudit = getCircleAudit;
  obj.getCommentList = getCommentList;
  obj.openmap = openmap;
  obj.getMenmberList = getMenmberList;
  obj.reviewComments = reviewComments;
  obj.scanQrcode = scanQrcode
  obj.creditRead = creditRead
  obj.getRandTopicList = getRandTopicList
  obj.VideoPlay = VideoPlay
  obj.getCircleListss=getCircleListss
  obj.userTap=userTap
}